package sindconsole.webapp.controller;

import common.annotation.Traced;
import common.exception.BadRequestException;
import common.exception.ConflictException;
import common.exception.InternalServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/api")
public class UploadController {

    @Value("${sindconsole.file-directory:files}")
    String fileDirectory;

    @Value("${sindconsole.file-context-path:/files}")
    String fileContextPath;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    @Traced("上载文件")
    public String upload(@RequestPart("file") MultipartFile file,
                         @RequestParam(value = "dest", required = false) String dest,
                         @RequestParam(value = "willOverwrite", defaultValue = "false") boolean willOverwrite) {
        if(file.isEmpty()) throw new BadRequestException("empty file");
        String destPath = StringUtils.hasText(dest) ? dest : file.getOriginalFilename();
        if(!destPath.startsWith("/")) destPath = "/" + destPath;
        File destFile = new File(fileDirectory, destPath);
        if(destFile.exists())
            if(willOverwrite)
                destFile.delete();
            else
                throw new ConflictException("dest file exists");
        try {
            destFile.getParentFile().mkdirs();
            file.transferTo(Paths.get(destFile.getAbsolutePath()));
            return fileContextPath + destPath;
        } catch(IOException x) {
            log.warn(x.getMessage(), x);
            throw new InternalServerException(x);
        }
    }

}
